<template>
  <div class="pie-chart-container">
    <div class="chart-header">
      <div class="header-icon">🥧</div>
      <div class="header-title">{{ title }}</div>
      <div class="refresh-btn" @click="refreshData">⟳</div>
    </div>
    <div ref="chartRef" class="chart-content"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'

interface PieData {
  name: string
  value: number
  color?: string
}

interface Props {
  title: string
  data: PieData[]
  height?: string
  showAnimation?: boolean
  showLegend?: boolean
  innerRadius?: string
  outerRadius?: string
}

const props = withDefaults(defineProps<Props>(), {
  height: '100%',
  showAnimation: true,
  showLegend: true,
  innerRadius: '40%',
  outerRadius: '70%'
})

const emit = defineEmits<{
  refresh: []
}>()

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 默认颜色方案
const defaultColors = [
  '#06b6d4', '#9d4edd', '#f472b6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#06d6a0'
]

const initChart = () => {
  if (!chartRef.value) return

  chartInstance = echarts.init(chartRef.value)

  const option = {
    backgroundColor: 'transparent',
    legend: props.showLegend ? {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      textStyle: {
        color: '#e6e6e6',
        fontSize: '0.8vw'
      },
      itemWidth: 12,
      itemHeight: 12,
      formatter: (name: string) => {
        return name
      }
    } : undefined,
    series: [
      {
        name: '',
        type: 'pie',
        radius: [props.innerRadius, props.outerRadius],
        center: ['40%', '50%'],
        data: props.data.map((item, index) => ({
          name: item.name,
          value: item.value,
          itemStyle: {
            color: item.color || defaultColors[index % defaultColors.length],
            borderColor: 'rgba(17, 34, 64, 0.8)',
            borderWidth: 2,
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 20,
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          label: {
            show: true,
            fontSize: '1vw',
            fontWeight: 'bold',
            color: '#ffffff'
          }
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}',
          fontSize: '0.8vw',
          color: '#e6e6e6',
          fontWeight: '500'
        },
        labelLine: {
          show: true,
          lineStyle: {
            color: 'rgba(100, 255, 218, 0.3)'
          }
        },
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: (idx: number) => idx * 100,
        animationDuration: 1000
      },
      // 内层旋转圆环
      {
        name: '内环',
        type: 'pie',
        radius: ['20%', '35%'],
        center: ['40%', '50%'],
        data: [{ value: 1, name: '' }],
        itemStyle: {
          color: 'rgba(100, 255, 218, 0.1)',
          borderColor: 'rgba(100, 255, 218, 0.3)',
          borderWidth: 1
        },
        label: { show: false },
        labelLine: { show: false },
        silent: true,
        animation: false
      }
    ],
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(17, 34, 64, 0.9)',
      borderColor: '#64ffda',
      borderWidth: 1,
      textStyle: {
        color: '#e6e6e6',
        fontSize: '0.8vw'
      },
      formatter: (params: any) => {
        return `
          <div style="padding: 0.5vw;">
            <div style="font-size: 1vw; color: #64ffda; margin-bottom: 0.3vw;">${params.name}</div>
            <div style="font-size: 1.2vw; color: #06b6d4; font-weight: bold;">${params.percent}%</div>
          </div>
        `
      }
    }
  }

  chartInstance.setOption(option)

  // 添加点击事件
  chartInstance.on('click', (params) => {
    console.log('Pie clicked:', params)
  })

  // 窗口大小变化时重新调整
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

const refreshData = () => {
  emit('refresh')
}

// 监听数据变化
watch(() => props.data, () => {
  if (chartInstance) {
    const option = {
      series: [{
        data: props.data.map((item, index) => ({
          name: item.name,
          value: item.value,
          itemStyle: {
            color: item.color || defaultColors[index % defaultColors.length]
          }
        }))
      }]
    }
    chartInstance.setOption(option, true)
  }
}, { deep: true })

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.pie-chart-container {
  position: relative;
  width: 100%;
  height: 100%;
  background: rgba(17, 34, 64, 0.4);
  border: 1px solid rgba(100, 255, 218, 0.3);
  border-radius: 0.5vw;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  overflow: hidden;
}

.pie-chart-container:hover {
  border-color: rgba(157, 78, 221, 0.5);
  box-shadow: 0 0 15px rgba(100, 255, 218, 0.3);
}

.chart-header {
  display: flex;
  align-items: center;
  padding: 0.8vw 1vw;
  background: rgba(17, 34, 64, 0.4);
  border-bottom: 1px solid rgba(100, 255, 218, 0.2);
}

.header-icon {
  font-size: 1.2vw;
  margin-right: 0.5vw;
  filter: drop-shadow(0 0 4px #64ffda);
}

.header-title {
  flex: 1;
  font-size: 1.1vw;
  color: #e6e6e6;
  font-weight: 500;
}

.refresh-btn {
  width: 1.5vw;
  height: 1.5vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(100, 255, 218, 0.1);
  border: 1px solid rgba(100, 255, 218, 0.3);
  border-radius: 50%;
  color: #64ffda;
  cursor: pointer;
  font-size: 0.8vw;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  background: rgba(100, 255, 218, 0.2);
  transform: rotate(180deg);
  box-shadow: 0 0 8px rgba(100, 255, 218, 0.5);
}

.chart-content {
  width: 100%;
  height: calc(100% - 3.5vw);
}

/* 响应式调整 */
@media (max-width: 1366px) {
  .header-title {
    font-size: 0.9vw;
  }
  .header-icon {
    font-size: 1vw;
  }
}

@media (min-width: 2560px) {
  .header-title {
    font-size: 1.3vw;
  }
  .header-icon {
    font-size: 1.4vw;
  }
}
</style>
